package ${packageName}.rest;
import com.boss.core.http.ResultEntity;
import ${packageName}.dto.${classInfo.className}DTO;
import ${packageName}.service.${classInfo.className}Service;
import com.boss.core.http.rest.errors.BadRequestAlertException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.jsqlparser.JSQLParserException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * Controller to ${classInfo.className}.
 *
 * @author ${authorName} ${.now?string('yyyy-MM-dd')}
 */
@Api(value = "${classInfo.className}Controller",tags = "#${classInfo.className}# 管理")
@RestController
@RequestMapping("/api")
public class ${classInfo.className}Controller {
    private static final Logger log = LoggerFactory.getLogger(${classInfo.className}Controller.class);
    @Autowired
    private ${classInfo.className}Service ${classInfo.className?uncap_first}Service;

    /**
     * {@code GET  /${classInfo.className?uncap_first}/:id} : get an {@link ${classInfo.className}DTO} by id.
     *
     * @param id the id of the entity to get.
     * @return the {@link ResultEntity} with status {@code 0 (OK)} and the {@link ${classInfo.className}DTO} in body, or status {@code 40404 (Not Found)}.
     */
    @ApiOperation(value = "根据ID获取#${classInfo.className}#", notes = "根据ID获取#${classInfo.className}#")
    @GetMapping("/${classInfo.className?uncap_first}/{id:.+}")
    public ResultEntity<${classInfo.className}DTO> find(@PathVariable Long id) {
        return ResultEntity.wrapOrNotFound(${classInfo.className?uncap_first}Service.find(id).map(${classInfo.className}DTO::new));

    }

    /**
     * {@code POST  /${classInfo.className?uncap_first}}  : Creates a new ${classInfo.className?uncap_first}.
     * <p>
     * Creates a new ${classInfo.className?uncap_first} if the name are not already used
     *
     * @param ${classInfo.className?uncap_first}DTO the ${classInfo.className?uncap_first} to create.
     * @return the {@link ResultEntity} with status {@code 0 (Created)} and with body the new ${classInfo.className?uncap_first}
     * @throws BadRequestAlertException {@code 40400 (Bad Request)} if the name is already in use.
     */
    @PostMapping("/${classInfo.className?uncap_first}")
//    @PreAuthorize("hasRole(\"" + AuthoritiesConstants.ADMIN + "\")")
    @ApiOperation(value = "新建#${classInfo.className}#", notes = "新建#${classInfo.className}#")
    public ResultEntity<${classInfo.className}DTO> create(@Valid @RequestBody ${classInfo.className}DTO ${classInfo.className?uncap_first}DTO) {
        if (log.isDebugEnabled()){
            log.debug("REST request to save ${classInfo.className} : {}",${classInfo.className?uncap_first}DTO);
        }

        if (${classInfo.className?uncap_first}DTO.getId() != null) {
            throw new BadRequestAlertException("A new ${classInfo.className} cannot already have an ID", "${classInfo.className}", "idexists");

        } else {
            ${classInfo.className}DTO new${classInfo.className} = ${classInfo.className}DTO.from(${classInfo.className?uncap_first}Service.create(${classInfo.className?uncap_first}DTO));
            return ResultEntity.ok(new${classInfo.className});

        }
    }

    /**
     * {@code POST  /${classInfo.className?uncap_first}}  : Update a  ${classInfo.className?uncap_first}.
     * <p>
     * Update  ${classInfo.className?uncap_first} if the id exits
     *
     * @param ${classInfo.className?uncap_first}DTO the ${classInfo.className?uncap_first} to update.
     * @return the {@link ResultEntity} with status {@code 0 (Created)} and with body the new ${classInfo.className?uncap_first}, or with status {@code 40400 (Bad Request)} if the id is null.
     * @throws BadRequestAlertException {@code 40400 (Bad Request)} if the ${classInfo.className} does not exist.
     */
    @PutMapping("/${classInfo.className?uncap_first}")
//    @PreAuthorize("hasRole(\"" + AuthoritiesConstants.ADMIN + "\")")
    @ApiOperation(value = "更新#${classInfo.className}#", notes = "更新#${classInfo.className}#")
    public ResultEntity<${classInfo.className}DTO> update(@Valid @RequestBody ${classInfo.className}DTO ${classInfo.className?uncap_first}DTO) {
        if (log.isDebugEnabled()){
            log.debug("REST request to update ${classInfo.className}DTO : {}",${classInfo.className?uncap_first}DTO);
        }

        ${classInfo.className}DTO new${classInfo.className} = ${classInfo.className}DTO.from(${classInfo.className?uncap_first}Service.update(${classInfo.className?uncap_first}DTO));
        return ResultEntity.ok(new${classInfo.className});
    }
    /**
     * {@code POST  /${classInfo.className?uncap_first}}  : Modify a  ${classInfo.className?uncap_first}.
     * <p>
     * Only Modify the DTO not null field for ${classInfo.className?uncap_first} if the id exits
     *
     * @param ${classInfo.className?uncap_first}DTO the ${classInfo.className?uncap_first} to modify.
     * @return the {@link ResultEntity} with status {@code 0 (Created)} and with body the new ${classInfo.className?uncap_first}, or with status {@code 40400 (Bad Request)} if the id is null.
     * @throws BadRequestAlertException {@code 40400 (Bad Request)} if the ${classInfo.className} does not exist.
     */
    @PutMapping("/${classInfo.className?uncap_first}/modify")
//    @PreAuthorize("hasRole(\"" + AuthoritiesConstants.ADMIN + "\")")
    @ApiOperation(value = "更新#${classInfo.className}#部分字段，只更新对应DTO里的not null字段", notes = "更新#${classInfo.className}#部分字段,只更新对应DTO里的not null字段")
    public ResultEntity<${classInfo.className}DTO> modify(@Valid @RequestBody ${classInfo.className}DTO ${classInfo.className?uncap_first}DTO) {
        if (log.isDebugEnabled()){
            log.debug("REST request to update ${classInfo.className}DTO : {}",${classInfo.className?uncap_first}DTO);
        }

        ${classInfo.className}DTO new${classInfo.className} = ${classInfo.className}DTO.from(${classInfo.className?uncap_first}Service.modify(${classInfo.className?uncap_first}DTO));
        return ResultEntity.ok(new${classInfo.className});
    }

    /**
     * {@code DELETE /${classInfo.className?uncap_first}/:id} : delete the ${classInfo.className}.
     *
     * @param id the ${classInfo.className?uncap_first} id.
     * @return the {@link ResultEntity} with status {@code 0 (SUCCESS)}.
     */
    @ApiOperation(value = "刪除#${classInfo.className}#", notes = "刪除#${classInfo.className}#")
    @DeleteMapping("/${classInfo.className?uncap_first}/{id:.+}")
//    @PreAuthorize("hasRole(\"" + AuthoritiesConstants.ADMIN + "\")")
    public ResultEntity<String> delete(@PathVariable Long id) {
        if (log.isDebugEnabled()){
            log.debug("REST request to delete ${classInfo.className}: {}",id);
        }
        ${classInfo.className?uncap_first}Service.delete(id);
        return ResultEntity.success();
    }

    /**
     * {@code GET  /${classInfo.className?uncap_first}/list} : get all {@link ${classInfo.className}DTO}.
     *
     * @return the {@link ResultEntity} with status {@code 0 (OK)} and the {@link ${classInfo.className}DTO} in body}.
     */
    @ApiOperation(value = "获取#${classInfo.className}#列表", notes = "获取#${classInfo.className}#列表")
    @GetMapping("/${classInfo.className?uncap_first}/list")
    // @PreAuthorize("hasRole(\"" + AuthoritiesConstants.ADMIN + "\")")
    public ResultEntity<Page<${classInfo.className}DTO>> list(Pageable pageable) {
        return ResultEntity.ok(${classInfo.className?uncap_first}Service.list(pageable));

    }


    /**
     * {@code GET  /product/adv/{whereClause}} : Advanced Search {@link ${classInfo.className}DTO}.
     * @param whereClause example: id between 1 and 3 or (id=1 or lastModifiedDate > 'yyyy-MM-dd HH:mm') and (createdBy=admin or createdBy like '*mdi*')
     *                    日期格式为：'yyyy-MM-dd HH:mm'；日期单引号括起来
     *                    模糊查询Like 用星号（*）而不是百分号（%）做模糊匹配；Like 里面的内容用单引号括起来
     *                    前端需要调用encodeURIComponent(whereClause)进行编码;
     * @param pageable
     * @return the {@link ResultEntity} with status {@code 0 (OK)} and the {@link ${classInfo.className}DTO} in body}.
     * @throws JSQLParserException
     */
    @ApiOperation(value = "高级搜索", notes = "whereClause example: id between 1 and 3 or (id=1 or lastModifiedDate > '2019-09-29 15:33') and (createdBy=admin or createdBy like '*mdi*') .\n<b style='color:red'>注意：</b>\n日期格式为：'yyyy-MM-dd HH:mm'，日期需要用单引号括起来；\n模糊查询Like 用星号（*）而不是百分号（%）做模糊匹配；Like 里面的内容需要用单引号括起来；\nHTML需要调用encodeURIComponent(whereClause)进行编码.")
    @GetMapping(value = "/${classInfo.className?uncap_first}/adv/{whereClause}")
    // @PreAuthorize("hasRole(\"" + AuthoritiesConstants.ADMIN + "\")")
    public ResultEntity<Page<${classInfo.className}DTO>> advancedSearch(@PathVariable String whereClause,Pageable pageable) throws JSQLParserException {
        return ResultEntity.ok(${classInfo.className?uncap_first}Service.advancedSearch(whereClause, pageable));
    }


}
